#pragma once

#include <functional>
#include "./../../source/server.hpp"

class EchoServer
{
public:
    EchoServer(int port)
        :_server(port)
    {
        _server.SetThreadCount(10);
        _server.InactiveReleaseEnable(10);
        _server.SetConnectedCb(std::bind(&EchoServer::ConnectedCb, this, std::placeholders::_1));
        _server.SetClosedCb(std::bind(&EchoServer::CloseCb, this, std::placeholders::_1));
        _server.SetMessageCb(std::bind(&EchoServer::MessageCb, this, std::placeholders::_1, std::placeholders::_2));
    }

    void Start() {
        _server.Start();
    }

private:
    void CloseCb(const PtrConnection& conn)
    {
        std::cout << "CLOSED: " << conn.get() << std::endl;
    }

    void ConnectedCb(const PtrConnection& conn)
    {
        // ns_log::lg(ns_log::LOG, "new--------"); //for debug
        std::cout << "CONNECTED: " << conn.get() << std::endl;
    }

    void MessageCb(const PtrConnection& conn, Buffer* buf)
    {
        uint64_t len = buf->GetReadableSpace();
        char* data = new char[len];
        buf->ReadAndPop(data, len);
        // std::cout << data << std::endl;
        std::string msg(data);
        conn->Send(msg.c_str(), msg.size());
        delete[] data;
        conn->ShutDown();
    }

private:
    TcpServer _server;
};
